package org.itboys.mobile.service.mysql.web;

import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieGroupRecordMapper;
import org.itboys.mobile.dao.TianJieWalletRecordMapper;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieGroup;
import org.itboys.mobile.entity.mysql.TianJieGroupRecord;
import org.itboys.mobile.entity.mysql.TianJieWalletRecord;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_金融_团队_service
 */
@Service
public class TianJieGroupService extends BaseMySqlService<TianJieGroup> {
    @Autowired
    private TianJieGroupRecordMapper groupRecordMapper;
    @Autowired
    private TianJieMemberService memberService;
    @Autowired
    private TianJieWalletRecordMapper walletRecordMapper;
    /**
     * 分页查询
     * @param request
     * @return
     */
    public PageResult<TianJieGroup> selectGroup(HttpServletRequest request){
        Map<String,Object> param =ParamUtil.packageMysqlPageParam(request,"name","captainName");
        List<TianJieGroup> groups = super.select(param);

        long count =super.count(param);
        //匹配该团队的充值金额
        List<Long> groupIds = new ArrayList<>();
        for(TianJieGroup group:groups){
            groupIds.add(group.getId());
        }
        param.clear();
        param.put("financeIsFinance",SundayCommonConstants.YES);
        param.put("financeGroupId in",groupIds);
        param.put("financeIsCaptain",SundayCommonConstants.YES);
        List<TianJieMember> members = memberService.list(param);
        List<Long> memberIds = new ArrayList<>();
        for(TianJieMember member:members){
            memberIds.add(member.getId());
        }
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            //只查充值，和后台拨付给队长的

            param.put("types", Arrays.asList(SundayCommonConstants.wallet_record_type_charge));
            // param.put("types",new Integer[]{SundayCommonConstants.wallet_record_type_charge, SundayCommonConstants.wallet_record_type_present_pc});
            param.put("memberIds",memberIds);
            param.put("status",SundayCommonConstants.YES);
            List<TianJieWalletRecord> walletRecords=walletRecordMapper.select(param);

            for(TianJieGroup group:groups){
                double chargeAmount = 0.00;
                double presentAmount =0.00;
                for(TianJieMember member:members){
                    for(TianJieWalletRecord walletRecord:walletRecords){
                        if(LongUtil.isNotZreo(member.getFinanceGroupId())&&
                                LongUtil.isNotZreo(walletRecord.getMemberId())&&
                                group.getId()==member.getFinanceGroupId().longValue()&&
                                member.getId()==walletRecord.getMemberId().longValue()){
                            //充值金额
                            if(walletRecord.getType()==SundayCommonConstants.wallet_record_type_charge){
                                chargeAmount+=walletRecord.getAmount().doubleValue();
                            }

                        }
                    }
                }
                group.setPresentAmount(new BigDecimal(presentAmount));
            }

        }
        return new PageResult<TianJieGroup>(groups,count);
    }

    /**
     *
     不分页查询
     * @return
     */
    public List<TianJieGroup> selectGroup(){
        Map<String,Object> param =new HashMap<String,Object>();
        return super.select(param);
    }
    /**
     * 新增或保存
     * @param group
     */
    public void saveGroup(TianJieGroup group){
        if(LongUtil.isNotZreo(group.getId())){
            super.update(group);
        }else{
            super.insert(group);
        }
    }

    /**
     * 单个查询
     * @param groupId
     * @return
     */
    public TianJieGroup findOne(long groupId){
        TianJieGroup group = null;
        if(LongUtil.isNotZreo(groupId)){

           group=super.find(groupId);
        }else{
           group=new TianJieGroup();
           group.setId(0l);
           group.setCaptainId(0l);
        }
        return group;
    }
    /**
     * 后台拨付给团队。
     */
    @Transactional
    public void present(Long groupId,BigDecimal amount){
        if(1==1){
            throw new ErrorException("功能已取消");
        }
        Long loginUserId = AdminSessionHolder.getAdminUserId();
        if(!LongUtil.isNotZreo(loginUserId)){
            throw new ErrorException("登录信息已失效，请重新登陆");
        }
        //更改团队主体金额
        TianJieGroup group=super.find(groupId);
        group.setPresentAmount(group.getPresentAmount().add(amount));
        super.update(group);
        //增加记录。被拨付人就是团队
        groupRecordMapper.insert(new TianJieGroupRecord( groupId,  groupId,  group.getName(),  amount, SundayCommonConstants.group_record_type_web));
    }

    /**
     * 设置团队队长
     * @param memberId
     * @param groupId
     */
    public void setCaptain(long memberId, long groupId){
        TianJieGroup group = super.find(groupId);
        TianJieMember member = memberService.getById(memberId);
        //检验团队是否有队长
        if(LongUtil.isNotZreo(group.getCaptainId())){
            throw new ErrorException("团队已经有队长");
        }
        group.setCaptainId(memberId);
        group.setCaptainName(member.getNickName());
        super.update(group);
        //修改用户信息
        member.setFinanceIsCaptain(SundayCommonConstants.YES);
        member.setFinanceGroupId(groupId);
        member.setFinanceGroupName(group.getName());
        memberService.updateExceptEmpty(memberId,member);
    }

    /**
     * 设置组织
     * @param memberId
     * @param groupId
     */
    public void setGroup(Long memberId,Long groupId){
        TianJieMember member= memberService.getById(memberId);
        if(LongUtil.isNotZreo(member.getFinanceGroupId())){
            throw new ErrorException("该用户已经属于团队："+member.getFinanceGroupName());
        }
        TianJieGroup group=super.find(groupId);
        member.setFinanceGroupId(groupId);
        member.setFinanceGroupName(group.getName());
        member.setFinanceIsFinance(SundayCommonConstants.YES);
        memberService.updateExceptEmpty(memberId,member);

    }
}
